<!--
 * @Description: 购物车页面
 * @Author: Gaq
 * @Date: 2022-11-03 17:24:45
 * @LastEditTime: 2022-11-29 20:05:44
 * @LastEditors: Gaq
-->
<script setup>
import request from "@/utils/request";
import router from "@/router";
import { ElMessage } from "element-plus";

const userInfo = ref({});
let cartList = ref([]);
let sum = ref(0);
let num = ref(-1);
let isEmpty = ref(false);
let disabled = ref(false);
userInfo.value = JSON.parse(localStorage.getItem("user"));
const { userId } = userInfo.value;
onBeforeMount(() => {
  getCart(userId);
  disabled.value = true;
});
// 样式的回调函数
const rowState = (arg) => {
  return {
    height: "60px",
  };
};

const toGoodDetail = (row) => {
  const goodId = row.goodsId;
  const routeUrl = router.resolve({
    name: "goodsdetail",
    query: { goodId },
  });
  window.open(routeUrl.href, "_blank");
};
let selectList = [];
const handleSum = (row) => {
  sum.value = 0;
  selectList = row;
  selectList.map((item) => {
    sum.value += item.price * item.num;
  });
  selectList.length == 0 ? (disabled.value = true) : (disabled.value = false);
  // console.log(selectList);
  length.value = selectList.length;
};
let length = ref(0);
const getCart = (id) => {
  request
    .get(`/cart/getPart/${id}`)
    .then((res) => {
      if (res.code == -1) {
        isEmpty.value = true;
      } else {
        cartList.value = res.data;
      }
    })
    .then(() => {
      cartList.value.forEach((value) => {
        request.get(`/goods/getOne/${value.goodsId}`).then((res) => {
          value["price"] = res.data.coverPrice;
        });
      });
    });
};
const changeNum = (row) => {
  request.put("/cart/updateOne", row).then(() => {
    return handleSum(selectList);
  });
};
const deleteCart = (value) => {
  request.delete(`/cart/deleteOne/${value.cartId}`).then((res) => {
    res.code == 0 ? getCart(userId) : ElMessage.error(res.msg);
  });
};
const deleteCarts = () => {
  selectList.map((item) => {
    deleteCart(item);
  });
  selectList = [];
  sum.value = 0;
  length.value = 0;
  disabled.value = true;
};
let order = {};
const getSelect = (row) => {
  console.log(row);
};
const goOrder = () => {
  router.push("/order");
  router.beforeEach((to, from, next) => {
    localStorage.setItem(
      "orderDetail",
      encodeURIComponent(JSON.stringify(selectList))
    );
    next();
  });
};
</script>

<template>
  <div>
    <div class="empty" v-show="isEmpty">
      <el-empty description="暂时没有您想要的商品~~" />
    </div>
    <div v-show="!isEmpty">
      <el-table :data="cartList" @select="handleSum" @select-all="handleSum">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column width="100">
          <template #default="scope">
            <el-image :src="scope.row.image" style="height: 80px" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="名称" show-overflow-tooltip>
          <template #default="scope">
            <span @click="toGoodDetail(scope.row)">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="单价">
          <template #default="scope">
            <span style="color: red">￥{{ scope.row.price }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="num" label="数量">
          <template #default="scope">
            <el-input-number
              v-model="scope.row.num"
              :min="1"
              :max="10"
              @change="changeNum(scope.row)"
            ></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #default="scope">
            <el-popconfirm
              title="确定删除吗？"
              @confirm="deleteCart(scope.row)"
            >
              <template #reference>
                <el-button size="small" type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <el-card style="position: fixed; bottom: 0px; width: 100%; height: 60px"
        ><div style="float: left">
          <button
            :class="disabled ? 'dis' : 'deleteItems'"
            @click="deleteCarts"
          >
            删除 ({{ length }})
          </button>
        </div>
        <div class="bottom">
          共{{ length }}件， 总价：<span style="color: red"
            >￥{{ sum.toFixed(2) }}</span
          >
          <button @click="goOrder">结算</button>
        </div>
      </el-card>
    </div>
  </div>
</template>

<style lang="less" scoped>
:deep(.el-table tbody tr:hover > td) {
  background-color: transparent !important;
  cursor: pointer;
  color: #972a2a;
}
.public {
  height: 30px;
  cursor: pointer;
  border: none;
  color: white;
  border-radius: 8%;
  background-color: rgb(242, 45, 0);
}
.dis {
  width: 60px;
  .public();
  background-color: grey;
  opacity: 0.5;
}
.deleteItems {
  width: 60px;
  .public();
}
.bottom {
  position: absolute;
  right: 230px;
  font-size: 20px;
  button {
    margin-left: 30px;
    cursor: pointer;
    margin-right: 30px;
    width: 100px;
    .public();
    span {
      vertical-align: middle;
    }
  }
}
</style>